<template>
  <div class="app-container">
    <template v-if="isLoggedIn">
      <div class="app-header">
        <h1>农业大棚监控系统</h1>
        <div class="user-info">
          <span v-if="username">{{ username }}</span>
          <el-button link @click="handleLogout">退出</el-button>
        </div>
      </div>
      <div class="app-main">
        <router-view></router-view>
      </div>
    </template>
    <template v-else>
      <router-view></router-view>
    </template>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { useRouter } from 'vue-router'
import { logout } from './api/user'
import { ElMessage } from 'element-plus'

const router = useRouter()
const isLoggedIn = computed(() => !!localStorage.getItem('token'))
const username = computed(() => {
  try {
    const userStr = localStorage.getItem('user')
    if (!userStr) return ''
    const userData = JSON.parse(userStr)
    return userData?.username || ''
  } catch (error) {
    console.error('解析用户信息失败:', error)
    localStorage.removeItem('user')
    return ''
  }
})

const handleLogout = async () => {
  try {
    localStorage.removeItem('token')
    localStorage.removeItem('user')
    localStorage.removeItem('redirectPath')
    router.push('/login')
    ElMessage.success('退出成功')
  } catch (error) {
    localStorage.removeItem('token')
    localStorage.removeItem('user')
    localStorage.removeItem('redirectPath')
    router.push('/login')
    ElMessage.success('退出成功')
  }
}
</script>

<style>
/* 全局样式 */
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

.app-container {
  width: 100vw;
  height: 100vh;
  background: #001529;
  color: #fff;
  display: flex;
  flex-direction: column;
  padding: 0;
  margin: 0;
  overflow: hidden;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
}

.app-header {
  height: 60px;
  background: rgba(0, 0, 0, 0.2);
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 20px;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

.app-header h1 {
  font-size: 20px;
  color: #1890ff;
  margin: 0;
}

.app-main {
  flex: 1;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  padding: 0;
  width: 100%;
  height: calc(100vh - 60px);
}

.user-info {
  display: flex;
  align-items: center;
  gap: 10px;
  color: rgba(255, 255, 255, 0.85);
}

.user-info .el-button {
  color: rgba(255, 255, 255, 0.65);
}

/* 添加一些全局样式 */
body {
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  background: #001529;
  margin: 0;
  padding: 0;
  overflow: hidden;
}

html {
  margin: 0;
  padding: 0;
  overflow: hidden;
}

::-webkit-scrollbar {
  width: 6px;
  height: 6px;
}

::-webkit-scrollbar-thumb {
  background: rgba(255, 255, 255, 0.2);
  border-radius: 3px;
}

::-webkit-scrollbar-track {
  background: transparent;
}
</style>
